package com.xzhuang.task.controller;

import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.quartz.CronTrigger;
import org.quartz.JobDetail;
import org.quartz.JobKey;
import org.quartz.Trigger;
import org.quartz.TriggerKey;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.xzhuang.task.quartz.ScheduleTask;
import com.xzhuang.task.service.TaskService;
import com.xzhuang.task.service.TaskServiceImpl;
import com.xzhuang.task.util.DBUtil;
import com.xzhuang.task.util.QuartzUtil;
import com.xzhuang.task.util.ResponseObject;

@Controller
public class Index extends BaseController {

	@Autowired
	private SchedulerFactoryBean schedulerFactoryBean;

	


	@RequestMapping(value = "/editjobcontroller")
	@ResponseBody
	public ResponseObject editJob(HttpServletRequest req) {
		ResponseObject ret = new ResponseObject();
		String jobName = req.getParameter("jobName");
		String cronstr = req.getParameter("cronstr");
		String httptype = req.getParameter("httptype");
		String isConcurrent = req.getParameter("isConcurrent");
		String jobDesc = req.getParameter("jobDesc");
		
		
		TaskService taskService = new TaskServiceImpl();
		ScheduleTask t = new ScheduleTask();

		try {

			if (jobName == null || jobName.length() == 0) {
				ret.setSuccess(false);
				ret.setErrorMsg("URL不能为空!");
				return ret;
			} else
		
			if (cronstr == null || cronstr.length() == 0) {
				ret.setSuccess(false);
				ret.setErrorMsg("quartz表达式不能为空!");
				return ret;
			} else {
				if (!QuartzUtil.isValidExpression(cronstr)) {
					ret.setSuccess(false);
					ret.setErrorMsg("您输入的quartz表达式: " + cronstr + " 格式不正确! 请参照示例添加!");
					return ret;
				}
			}
			
			t.setCronExpression(cronstr);
			t.setJobName(jobName);
			t.setIsConcurrent(isConcurrent);
			if(jobDesc != null && jobDesc.trim().length() > 0){
				//jobDesc = new String(jobDesc.getBytes("ISO8859-1"),"UTF-8");
				
				if(jobDesc.indexOf("|") != -1){
					ret.setErrorMsg("您输入的任务描述内容里面不能包含:\"|\" 字符,请修改,!"); return ret;
				}
				if(jobDesc.length() > 20){
					ret.setErrorMsg("您输入的任务描述内容长度不能大于20个汉字,请修改,!"); return ret;
				}
				
				
				t.setDescription(httptype + "|" + jobDesc);
			}else{
				ret.setErrorMsg("请输入任务描述,方便以后查询修改！!"); return ret;
				//t.setDescription(httptype);
			}
			t.setJobStatus("1");
			taskService.updateTaskTrigger(t);
		} catch (Exception e) {
			ret.setSuccess(false);
			String msg = e.getMessage();
			if (msg != null && msg.length() > 150)
				msg.substring(0, 150);
			ret.setErrorMsg("任务添加失败,详情：" + msg);
			return ret;
		}
		ret.setSuccess(true);
		return ret;
	}

	@RequestMapping(value = "/addjobcontroller")
	@ResponseBody
	public ResponseObject addJob(HttpServletRequest req) {
		ResponseObject ret = new ResponseObject();
		String jobName = req.getParameter("jobName");
		String cronstr = req.getParameter("cronstr");
		String httptype = req.getParameter("httptype");
		String isConcurrent = req.getParameter("isConcurrent");
		String jobDesc = req.getParameter("jobDesc");
		
		TaskService taskService = new TaskServiceImpl();
		ScheduleTask t = new ScheduleTask();
		try {
			if (jobName == null || jobName.length() == 0) {
				ret.setSuccess(false);
				ret.setErrorMsg("URL不能为空!");
				return ret;
			} else
			// 暂不校验,因为后面扩展后,这个字段不一定是URL
			/*
			 * { if (!QuartzUtil.isURL(jobName)) { ret.setSuccess(false);
			 * ret.setErrorMsg("您输入的URL地址: " + cronstr + " 格式不正确!"); return ret;
			 * } }
			 */
			if (cronstr == null || cronstr.length() == 0) {
				ret.setSuccess(false);
				ret.setErrorMsg("quartz表达式不能为空!");
				return ret;
			} else {
				if (!QuartzUtil.isValidExpression(cronstr)) {
					ret.setSuccess(false);
					ret.setErrorMsg("您输入的quartz表达式: " + cronstr + " 格式不正确! 请参照示例添加!");
					return ret;
				}
			}
			t.setCronExpression(cronstr);
			t.setJobName(jobName);
			t.setIsConcurrent(isConcurrent);// 1 并行 ，其它值为串行
			if(jobDesc != null && jobDesc.trim().length() > 0){
				//jobDesc = new String(jobDesc.getBytes("ISO8859-1"),"UTF-8");
				if(jobDesc.indexOf("|") != -1){
					ret.setErrorMsg("您输入的任务描述内容里面不能包含:\"|\" 字符, 请修改,!"); return ret;
				}
				if(jobDesc.length() > 20){
					ret.setErrorMsg("您输入的任务描述内容长度不能大于20个汉字,请修改,!"); return ret;
				}
				t.setDescription(httptype + "|" + jobDesc);
			}else{
				ret.setErrorMsg("请输入任务描述,方便以后查询修改！!"); return ret;
				//t.setDescription(httptype);
			}
			
			t.setJobStatus("1");

			taskService.addTask(t);
		} catch (Exception e) {

			ret.setSuccess(false);
			String msg = e.getMessage();
			if (msg != null && msg.length() > 150)
				msg.substring(0, 150);
			ret.setErrorMsg("任务添加失败,详情：" + msg);
			return ret;
		}
		ret.setSuccess(true);
		return ret;
	}

	@RequestMapping(value = "/login")
	@ResponseBody
	public ResponseObject index(HttpServletRequest request, String username, String password) {
		ResponseObject ret = new ResponseObject();
		try {
			String pa = request.getSession().getServletContext().getRealPath("/WEB-INF/classes");
			if (pa != null && pa.length() > 0) {
				if (!"\\".equals(pa.subSequence(pa.length() - 1, pa.length()))) {
					Properties prop = System.getProperties();
					String os = prop.getProperty("os.name");

					// os.startWith("win") || os.startWith("Win") == windows操作系统

					if (os.indexOf("win") != -1 || os.indexOf("Win") != -1) {
						pa = pa + "\\pa.txt";
					} else {
						pa = pa + "/pa.txt";
					}

				} else {
					pa = pa + "pa.txt";
				}
			} else {
				ret.setSuccess(false);
				ret.setErrorMsg("");
				return ret;
			}
			String pass = QuartzUtil.getConfigValue(pa);
			if (username == null || username.trim().length() == 0) {
				ret.setSuccess(false);
				ret.setErrorMsg("用户名不能为空!");
				return ret;
			}
			if (password == null || password.trim().length() == 0) {
				ret.setSuccess(false);
				ret.setErrorMsg("登录密码不能为空!");
				return ret;
			}
			if (!"admin".equals(username)) {
				ret.setSuccess(false);
				ret.setErrorMsg("用户名错误!");
				return ret;
			}

			if (!password.equals(pass)) {
				ret.setSuccess(false);
				ret.setErrorMsg("密码错误!");
				return ret;
			}
			request.getSession().setAttribute(QuartzUtil.USERINFO, "admin");
			ret.setSuccess(true);
			return ret;
		} catch (Exception e) {
			e.printStackTrace();
			ret.setSuccess(false);
			ret.setErrorMsg("登录错误,请稍后重试!!");
			return ret;
		}
	}

	@RequestMapping(value = "/getAllJobList")
	@ResponseBody
	public ResponseObject getAllJobList() {
		ResponseObject ret = new ResponseObject();
		return ret;
	}

	@RequestMapping(value = "/getAllJobList3")
	@ResponseBody
	public Map getAllJobList3(HttpServletRequest req) {
		Map rmap = new HashMap();
		String pageSizes = req.getParameter("iDisplayLength");
		int ps = (pageSizes == null ? 13 : Integer.parseInt(pageSizes));
		String pageIndexs = req.getParameter("sEcho");
		int sEcho = (pageIndexs == null ? 1 : Integer.parseInt(pageIndexs));
		String displayStart = req.getParameter("iDisplayStart");
		int pd = (displayStart == null ? 0 : Integer.parseInt(displayStart));
				
		TaskService taskService = new TaskServiceImpl();
		String op = "";
		
		String q_key_word = req.getParameter("q_key_word");
		
		try {
			int sd[] = getLimitStartAndEnd(pd, ps);
			List<List> testlist = new ArrayList();
			List<ScheduleTask> tasklist = taskService.findExeTaskList();
			//int zcount = tasklist == null ? 0 : tasklist.size();
			List<String> tempList;// resume
			for (ScheduleTask st : tasklist) {
				op = "<button type='button' class='btn btn-success btn-sm' onclick=\"fn_pausejob('" + st.getJobName() + "');\">暂停</button>&nbsp;" + "<button type='button' class='btn btn-danger btn-sm' onclick=\"fn_resumejob('" + st.getJobName() + "');\">恢复</button>&nbsp;" + "<button type='button' class='btn btn-success btn-sm' onclick=\"fn_toeditjob('" + st.getJobName() + "');\">修改</button>&nbsp;" + "<button type='button' class='btn btn-danger btn-sm' onclick=\"fn_deletejob('" + st.getJobName()
						+ "');\">删除</button>&nbsp;";
				TriggerKey triggerKey = TriggerKey.triggerKey(st.getJobName(), st.getJobGroup());
			
				CronTrigger trigger = (CronTrigger) taskService.getScheduler().getTrigger(triggerKey);
				Trigger.TriggerState triggerState = taskService.getScheduler().getTriggerState(trigger.getKey());

				tempList = new ArrayList<String>();
				tempList.add(st.getJobName());
				tempList.add(QuartzUtil.getTrigerStateName(triggerState.name()));
				
				if ("1".equals(QuartzUtil.getExtendParam(st.getDescription())[0])) {
					tempList.add("GET");
				} else {
					tempList.add("POST");
				}
				tempList.add(QuartzUtil.getFormatDateString(trigger.getStartTime()));
				tempList.add(QuartzUtil.getFormatDateString(trigger.getPreviousFireTime()));
				tempList.add(QuartzUtil.getFormatDateString(trigger.getNextFireTime()));
				
				if(QuartzUtil.getExtendParam(st.getDescription()) != null && QuartzUtil.getExtendParam(st.getDescription()).length > 1){
					tempList.add(QuartzUtil.getExtendParam(st.getDescription())[1]);
				}
				
				tempList.add(op);
				
				//下面这段代码 IF END IF 是在控制层，进行结果集筛选，目的是实现按任务描述查询任务列表。会让分页信息不准确，不过不影响使用
				if(StringUtils.isNotBlank(q_key_word) && StringUtils.isNotBlank(QuartzUtil.getExtendParam(st.getDescription())[1])) {
					String job_desc = QuartzUtil.getExtendParam(st.getDescription())[1];
					if(job_desc.indexOf(q_key_word) >= 0) {
						testlist.add(tempList);
					}
				}else {
					testlist.add(tempList);
				}				
				
			}
			int zcount = testlist == null ? 0 : testlist.size();
			List<List<String>> list = new ArrayList<List<String>>();
			Map map = new HashMap();
			List lists = new ArrayList();
			for (int i = 0; testlist != null && i < testlist.size(); i++) {
				List lt = testlist.get(i);
				if (i >= sd[0] && i <= sd[1]) {
					list.add(lt);
				}
			}
			rmap.put("sEcho", sEcho);
			rmap.put("iTotalDisplayRecords", zcount);
			rmap.put("iTotalRecords", zcount);
			rmap.put("aaData", list);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return rmap;
	}

	@RequestMapping(value = "/searchlog")
	@ResponseBody
	public Map searchlog(HttpServletRequest req) {
		ResponseObject ret = new ResponseObject();
		String pageSizes = req.getParameter("iDisplayLength");
		int ps = (pageSizes == null ? 17 : Integer.parseInt(pageSizes));

		String pageIndexs = req.getParameter("sEcho");
		int sEcho = (pageIndexs == null ? 1 : Integer.parseInt(pageIndexs));

		String displayStart = req.getParameter("iDisplayStart");
		int pd = (displayStart == null ? 0 : Integer.parseInt(displayStart));

		String jobName = req.getParameter("jobName");
		String begin = req.getParameter("begin");
		String end = req.getParameter("end");

		try {

			DBUtil db = new DBUtil();
			return db.searchLog(begin, end, jobName, pd, ps, String.valueOf(sEcho));
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}

	}

	@RequestMapping(value = "/toaddjob")
	public String toAddJob() {
		return "addjob";
	}

	@RequestMapping(value = "/toindex")
	public String toindex() {
		return "index";
	}

	@RequestMapping(value = "/toeditjob")
	public ModelAndView toEditJob(String jobName) {
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			if(jobName != null && jobName.length() > 0){
				jobName = URLDecoder.decode(jobName,"utf-8");
				
			}
			TaskService taskService = new TaskServiceImpl();
			TriggerKey triggerKey = TriggerKey.triggerKey(jobName, QuartzUtil.defaultGroupName);
			
			CronTrigger trigger = (CronTrigger) taskService.getScheduler().getTrigger(triggerKey);
			Trigger.TriggerState triggerState = taskService.getScheduler().getTriggerState(trigger.getKey());
			String cronStr = trigger.getCronExpression();
			String httptype = trigger.getDescription();
			JobDetail jobDetail = taskService.getScheduler().getJobDetail(new JobKey(jobName, QuartzUtil.defaultGroupName));
			String className = jobDetail.getJobClass().getName();
			String ty = QuartzUtil.getExtendParam(httptype)[0];
			map.put("jobName", jobName);
			map.put("cronStr", cronStr);
			map.put("httptype", ty);
			if(QuartzUtil.getExtendParam(httptype).length > 1){
				map.put("jobDesc", QuartzUtil.getExtendParam(httptype)[1]);
			}
			if ("com.xzhuang.task.quartz.QuartzJobFactoryDisallowConcurrentExecution".equals(className)) {
				map.put("isConcurrent", "0");
			} else {
				map.put("isConcurrent", "1");
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
		return new ModelAndView("editjob", map);
	}

	@RequestMapping(value = "/geterrormsg")
	@ResponseBody
	public String getErrorMsg(String logid) {

		String msg = "";
		try {
			DBUtil db = new DBUtil();
			msg = db.searchLogMsg(logid);
		} catch (Exception e) {
			msg = "查询错误,请重试!";
		}

		return msg;
	}

	@RequestMapping(value = "/deleteJob")
	@ResponseBody
	public ResponseObject deleteJob(String jobName) {
		ResponseObject ret = new ResponseObject();
		TaskService taskService = new TaskServiceImpl();

		if (jobName == null || jobName.length() == 0) {
			ret.setErrorMsg("URL 不能为空");
			ret.setSuccess(false);
			return ret;
		}
		ScheduleTask st = new ScheduleTask();
		st.setJobName(jobName);
		st.setJobGroup(QuartzUtil.defaultGroupName);// 本系统不允许用户自定义JOBGROUP，所以这里可以写死为：“DEFAULT”
		try {
			taskService.deleteTask(st,QuartzUtil.defaultGroupName);
			ret.setSuccess(true);
			return ret;
		} catch (Exception e) {
			e.printStackTrace();
			String msg = e.getMessage();
			if (msg != null && msg.length() > 150)
				msg.substring(0, 150);

			ret.setErrorMsg("删除错误 详情:" + msg);
			ret.setSuccess(false);
			return ret;
		}
	}

	// resumeTask
	@RequestMapping(value = "/resumeJob")
	@ResponseBody
	public ResponseObject resumeJob(String jobName) {
		ResponseObject ret = new ResponseObject();
		TaskService taskService = new TaskServiceImpl();
		if (jobName == null || jobName.length() == 0) {
			ret.setErrorMsg("URL 不能为空");
			ret.setSuccess(false);
			return ret;
		}
		ScheduleTask st = new ScheduleTask();
		st.setJobName(jobName);
		st.setJobGroup(QuartzUtil.defaultGroupName);// 本系统不允许用户自定义JOBGROUP，所以这里可以写死为：“DEFAULT”
		try {
			taskService.resumeTask(st);
			ret.setSuccess(true);
			return ret;
		} catch (Exception e) {
			e.printStackTrace();
			String msg = e.getMessage();
			if (msg != null && msg.length() > 150)
				msg.substring(0, 150);

			ret.setErrorMsg("删除错误 详情:" + msg);
			ret.setSuccess(false);
			return ret;
		}
	}

	@RequestMapping(value = "/pauseJob")
	@ResponseBody
	public ResponseObject pauseJob(String jobName) {
		ResponseObject ret = new ResponseObject();
		TaskService taskService = new TaskServiceImpl();
		if (jobName == null || jobName.length() == 0) {
			ret.setErrorMsg("URL 不能为空");
			ret.setSuccess(false);
			return ret;
		}
		ScheduleTask st = new ScheduleTask();
		st.setJobName(jobName);
		st.setJobGroup(QuartzUtil.defaultGroupName);// 本系统不允许用户自定义JOBGROUP，所以这里可以写死为：“DEFAULT”
		try {
			taskService.pauseTask(st);
			ret.setSuccess(true);
			return ret;
		} catch (Exception e) {
			e.printStackTrace();
			String msg = e.getMessage();
			if (msg != null && msg.length() > 150)
				msg.substring(0, 150);

			ret.setErrorMsg("删除错误 详情:" + msg);
			ret.setSuccess(false);
			return ret;
		}
	}

	@RequestMapping(value = "/testjob")
	@ResponseBody
	public ResponseObject testjob(String jobName) {
		return null;
	}
}
